<template>
  <div class="container">
    <div class="input-container">
      <div class="ghhjj">
      <span class="police1">设备编号</span>
      <el-input
        v-model="input"
        placeholder="请输入设备编号"
        size="middle"
        class="input-box"
      ></el-input>
                <div class="block">
                  <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                  </el-date-picker>
                </div>
      <el-button
        size="middle"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
        class="search-btn"
        >搜索</el-button
      >
      <el-button
        size="middle"
        type="default"
        icon="el-icon-refresh"
        @click="handleReset"
        class="reset-btn"
        >重置</el-button
      >
    </div>
        
  </div>
    <div class="option">
      <el-button
        size="middle"
        type="primary"
        icon="el-icon-plus"
        @click="adddialogVisible = true"
        class="add-btn"
        >增加</el-button
      >
      <el-button
        size="middle"
        type="danger"
        icon="el-icon-delete"
        @click="handleDelete4"
        class="delete-btn"
        >删除</el-button
      >
    </div>
    <div class="table-container">
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          prop="deviceId"
          label="设备编号"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="productName"
          label="产品名称"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="machineSn"
          label="机械编号"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="ofcompany"
          label="所属公司"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="deviceCrack"
          label="设备密钥"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="deviceStatus"
          label="设备状态"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="deviceAddress"
          label="设备地址"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="deviceTypeId"
          label="设备类型"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="activationTime"
          label="激活时间"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="lastOnlineTime"
          label="最后上线时间"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="120"
        ></el-table-column>
          <el-table-column label="操作1">
          <template slot-scope="scope">
           
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
           
          </template>
        </el-table-column>
        <el-table-column label="操作2">
          <template slot-scope="scope">
          
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
    
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      title="增加报警"
      :visible.sync="adddialogVisible"
      width="30%"
      :before-close="handleDialogClose"
    >
    <el-form
  ref="form"
  :model="formData"
  :rules="formRules"
  label-width="80px"
>
  <el-form-item label="设备编号" prop="deviceId">
    <el-input v-model="formData.deviceId"></el-input>
  </el-form-item>
  <el-form-item label="产品名称" prop="productName">
    <el-input v-model="formData.productName"></el-input>
  </el-form-item>
  <el-form-item label="机械编号" prop="machineSn">
    <el-input v-model="formData.machineSn"></el-input>
  </el-form-item>
  <el-form-item label="所属公司" prop="ofcompany">
    <el-input v-model="formData.ofcompany"></el-input>
  </el-form-item>
  <el-form-item label="设备密钥" prop="deviceCrack">
    <el-input v-model="formData.deviceCrack"></el-input>
  </el-form-item>
  <el-form-item label="设备状态" prop="deviceStatus">
    <el-select v-model="formData.deviceStatus" placeholder="请选择">
      <el-option label="在线" value="在线"></el-option>
      <el-option label="离线" value="离线"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="设备地址" prop="deviceAddress">
    <el-input v-model="formData.deviceAddress"></el-input>
  </el-form-item>
  <el-form-item label="设备类型" prop="deviceTypeId">
    <el-select v-model="formData.deviceTypeId" placeholder="请选择">
      <el-option label="设备" value="1"></el-option>
      <el-option label="网关" value="2"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="激活时间" prop="activationTime">
    <el-date-picker v-model="formData.activationTime" type="datetime" placeholder="选择时间"></el-date-picker>
  </el-form-item>
  <el-form-item label="最后上线时间" prop="lastOnlineTime">
    <el-date-picker v-model="formData.lastOnlineTime" type="datetime" placeholder="选择时间"></el-date-picker>
  </el-form-item>
  <el-form-item label="创建时间" prop="createTime">
    <el-date-picker v-model="formData.createTime" type="datetime" placeholder="选择时间"></el-date-picker>
  </el-form-item>
</el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="编辑报警"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleDialogClose"
    >
    <el-form
  ref="form"
  :model="formData"
  :rules="formRules"
  label-width="80px"
>
<el-form-item label="设备编号" prop="deviceId">
    <el-input v-model="formData.deviceId" :readonly="true"></el-input>
  </el-form-item>
  <el-form-item label="产品名称" prop="productName">
    <el-input v-model="formData.productName"></el-input>
  </el-form-item>
  <el-form-item label="机械编号" prop="machineSn">
    <el-input v-model="formData.machineSn"></el-input>
  </el-form-item>
  <el-form-item label="所属公司" prop="ofcompany">
    <el-input v-model="formData.ofcompany"></el-input>
  </el-form-item>
  <el-form-item label="设备密钥" prop="deviceCrack">
    <el-input v-model="formData.deviceCrack"></el-input>
  </el-form-item>
  <el-form-item label="设备状态" prop="deviceStatus">
    <el-select v-model="formData.deviceStatus" placeholder="请选择">
      <el-option label="在线" value="在线"></el-option>
      <el-option label="离线" value="离线"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="设备地址" prop="deviceAddress">
    <el-input v-model="formData.deviceAddress"></el-input>
  </el-form-item>
  <el-form-item label="设备类型" prop="deviceTypeId">
    <el-select v-model="formData.deviceTypeId" placeholder="请选择">
      <el-option label="设备" value="1"></el-option>
      <el-option label="网关" value="2"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="激活时间" prop="activationTime">
    <el-date-picker v-model="formData.activationTime" type="datetime" placeholder="选择时间"></el-date-picker>
  </el-form-item>
  <el-form-item label="最后上线时间" prop="lastOnlineTime">
    <el-date-picker v-model="formData.lastOnlineTime" type="datetime" placeholder="选择时间"></el-date-picker>
  </el-form-item>
  <el-form-item label="创建时间" prop="createTime">
    <el-date-picker v-model="formData.createTime" type="datetime" placeholder="选择时间"></el-date-picker>
  </el-form-item>
</el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[5,10,15, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
import moment from "moment-timezone";
import Axios from "axios";
export default {
  productName: 'TableExample',
  data() {
    return {
      input: "",
      tableData: [],
      selectedRow: null,
      cunchushu1: [],
      dateRange: [],
      selectedNames1: [], // 存放选中行的 name 变量的全局数组
      multipleSelection: [],
      adddialogVisible: false,
      dialogVisible: false,
      pageNum: 1,
      pageSize: 10,
      total:400,
      formData: {
      deviceId: "",
      productName: "",
      machineSn: "",
      ofcompany: "",
      deviceCrack: "",
      deviceStatus: "",
      deviceAddress: "",
      deviceTypeId: "",
      activationTime: "",
      lastOnlineTime: "",
      createTime: "",
    },
    selectedRow: {
      deviceId: "",
      productName: "",
      machineSn: "",
      ofcompany: "",
      deviceCrack: "",
      deviceStatus: "",
      deviceAddress: "",
      deviceTypeId: "",
      activationTime: "",
      lastOnlineTime: "",
      createTime: "",
    },
    formRules: {
      deviceId: [
        { required: true, message: "请输入设备编号", trigger: "blur" },
      ],
      productName: [
        { required: true, message: "请输入产品名称", trigger: "blur" },
      ],
      machineSn: [
        { required: true, message: "请输入机械编号", trigger: "blur" },
      ],
      ofcompany: [
        { required: true, message: "请输入所属公司", trigger: "blur" },
      ],
      deviceCrack: [
        { required: true, message: "请输入设备密钥", trigger: "blur" },
      ],
      deviceStatus: [
        { required: true, message: "请选择设备状态", trigger: "change" },
      ],
      deviceAddress: [
        { required: true, message: "请输入设备地址", trigger: "blur" },
      ],
      deviceTypeId: [
        { required: true, message: "请选择设备类型", trigger: "change" },
      ],
      activationTime: [
        { required: true, message: "请选择激活时间", trigger: "change" },
      ],
      lastOnlineTime: [
        { required: true, message: "请选择最后上线时间", trigger: "change" },
      ],
      createTime: [
        { required: true, message: "请选择创建时间", trigger: "change" },
      ],
    },
  };
  },
  created(){
      Axios.get("http://localhost:8080/device")
        .then((res) => {
          console.log(res);
          /*for (let i = 0; i < res.data.data.length; i++) {
          const selectedTime = moment(res.data.data[i].activationTime);
          const deviceTimeZone = moment.tz.guess();
          const localTime = selectedTime.tz(deviceTimeZone).format("YYYY-MM-DD HH:mm:ss");
          res.data.data[i].activationTime = localTime;

          const selectedTime2 = moment(res.data.data[i].lastOnlineTime);
          const deviceTimeZone2 = moment.tz.guess();
          const localTime2 = selectedTime2.tz(deviceTimeZone2).format("YYYY-MM-DD HH:mm:ss");
          res.data.data[i].lastOnlineTime = localTime2;

          const selectedTime3 = moment(res.data.data[i].createTime);
          const deviceTimeZone3 = moment.tz.guess();
          const localTime3 = selectedTime3.tz(deviceTimeZone3).format("YYYY-MM-DD HH:mm:ss");
          res.data.data[i].createTime = localTime3;
        }*/
          this.tableData = res.data;
          this.total = this.tableData.length;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  mounted() {

    if (!this.tableData.length) {
  Axios.get("http://localhost:8080/device")
    .then((res) => {
      console.log(res);
      for (let i = 0; i < res.data.data.length; i++) {
          const selectedTime = moment(res.data.data[i].activationTime);
          const deviceTimeZone = moment.tz.guess();
          const localTime = selectedTime.tz(deviceTimeZone).format("YYYY-MM-DD HH:mm:ss");
          res.data.data[i].activationTime = localTime;

          const selectedTime2 = moment(res.data.data[i].lastOnlineTime);
          const deviceTimeZone2 = moment.tz.guess();
          const localTime2 = selectedTime2.tz(deviceTimeZone2).format("YYYY-MM-DD HH:mm:ss");
          res.data.data[i].lastOnlineTime = localTime2;

          const selectedTime3 = moment(res.data.data[i].createTime);
          const deviceTimeZone3 = moment.tz.guess();
          const localTime3 = selectedTime3.tz(deviceTimeZone3).format("YYYY-MM-DD HH:mm:ss");
          res.data.data[i].createTime = localTime3;
        }
      this.tableData = res.data.data;
    })
    .catch((err) => {
      console.log(err);
    });
}
},
  methods: {
    page(){
      this.dateRange=[],
        Axios.get(`http://localhost:8080/device`)
        .then((res) => {
          console.log(res);
          for (let i = 0; i < res.data.data.length; i++) {
          const selectedTime = moment(res.data.data[i].activationTime);
          const deviceTimeZone = moment.tz.guess();
          const localTime = selectedTime.tz(deviceTimeZone).format("YYYY-MM-DD HH:mm:ss");
          res.data.data[i].activationTime = localTime;

          const selectedTime2 = moment(res.data.data[i].lastOnlineTime);
          const deviceTimeZone2 = moment.tz.guess();
          const localTime2 = selectedTime2.tz(deviceTimeZone2).format("YYYY-MM-DD HH:mm:ss");
          res.data.data[i].lastOnlineTime = localTime2;

          const selectedTime3 = moment(res.data.data[i].createTime);
          const deviceTimeZone3 = moment.tz.guess();
          const localTime3 = selectedTime3.tz(deviceTimeZone3).format("YYYY-MM-DD HH:mm:ss");
          res.data.data[i].createTime = localTime3;
        }
          this.tableData = res.data.data;
          // this.total = this.tableData.length;
        })
        .catch((err) => {
          console.log(err);
        });
      },
    handleReset(){
        this.input = ''
        this.dateRange=[]
        Axios.get("http://localhost:8080/device")
        .then((res) => {
          console.log(res);
          for (let i = 0; i < res.data.data.length; i++) {
          const selectedTime = moment(res.data.data[i].activationTime);
          const deviceTimeZone = moment.tz.guess();
          const localTime = selectedTime.tz(deviceTimeZone).format("YYYY-MM-DD HH:mm:ss");
          res.data.data[i].activationTime = localTime;

          const selectedTime2 = moment(res.data.data[i].lastOnlineTime);
          const deviceTimeZone2 = moment.tz.guess();
          const localTime2 = selectedTime2.tz(deviceTimeZone2).format("YYYY-MM-DD HH:mm:ss");
          res.data.data[i].lastOnlineTime = localTime2;

          const selectedTime3 = moment(res.data.data[i].createTime);
          const deviceTimeZone3 = moment.tz.guess();
          const localTime3 = selectedTime3.tz(deviceTimeZone3).format("YYYY-MM-DD HH:mm:ss");
          res.data.data[i].createTime = localTime3;
        }
          this.tableData=res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
        
      },

      handleSearch() {
      if (!this.input && !this.dateRange[0] && !this.dateRange[1]) {
      this.$message.warning("请输入设备编号或日期限制");
      return;
      }
      if (this.dateRange[0] &&this.dateRange[1]) {
      //将日期转换为设备所在时区的本地时间
      const selectedTime = moment(this.dateRange[0]);
      const deviceTimeZone = moment.tz.guess();
      const localTime = selectedTime.tz(deviceTimeZone).format("YYYY-MM-DD HH:mm:ss");
      this.dateRange[0] = localTime;
      //将日期转换为设备所在时区的本地时间
      const selectedTime2 = moment(this.dateRange[1]);
      const deviceTimeZone2 = moment.tz.guess();
      const localTime2 = selectedTime2.tz(deviceTimeZone2).format("YYYY-MM-DD HH:mm:ss");
      this.dateRange[1] = localTime2;
      }
        const params = {
        input: this.input,
        startDate: this.dateRange[0],
        endDate: this.dateRange[1],
      };
      Axios.get("http://localhost:8080/device/search", {
        params: params
      }).then(response => {
        // 处理返回的数据
        for (let i = 0; i < response.data.data.length; i++) {
                const selectedTime = moment(response.data.data[i].updateTime);
                const deviceTimeZone = moment.tz.guess();
                const localTime = selectedTime.tz(deviceTimeZone).format("YYYY-MM-DD HH:mm:ss");
                response.data.data[i].updateTime = localTime;
              }
        this.tableData = response.data.data;
      }).catch(error => {
        // 处理请求失败的情况
        console.error(error);
      });
      },
    handleSelectionChange(val) {
    this.multipleSelection = val,
    this.selectedNames1=this.multipleSelection,
    console.log(this.selectedNames1)
    },
    handleEdit(index, row) {
      // 将选中行的数据复制到临时编辑数据中
  this.selectedRow = Object.assign({}, row);
  // 将选中行的数据复制到表单数据中，用于在编辑对话框中显示
  this.formData = Object.assign({}, this.selectedRow);
  this.dialogVisible = true;
    },
    handleDelete(index, row) {
      this.$confirm('确定删除该设备记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 从表格中删除该行数据
        this.tableData.splice(index, 1);
        // 发送DELETE请求将该行数据从数据库中删除
        Axios.delete(`http://localhost:8080/device/delete/${row.deviceId}`).then(response => {
          console.log(response.data);
        }).catch(error => {
          console.error(error);
        });
      }).catch(() => {
        // 取消删除操作
      });
    },
    handleDialogClose(done) {
      if (this.dialogVisible) {
        this.$confirm("确认关闭？")
          .then(() => {
            done();
          })
          .catch(() => {});
      } else {
        done();
      }
    },
    handleAddSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log(this.formData);
         //将日期转换为设备所在时区的本地时间
          const selectedTime = moment(this.formData.activationTime);
          const deviceTimeZone = moment.tz.guess();
          const localTime = selectedTime.tz(deviceTimeZone).format("YYYY-MM-DD HH:mm:ss");
          this.formData.activationTime = localTime;
           //将日期转换为设备所在时区的本地时间
           const selectedTime2 = moment(this.formData.lastOnlineTime);
          const deviceTimeZone2 = moment.tz.guess();
          const localTime2 = selectedTime2.tz(deviceTimeZone2).format("YYYY-MM-DD HH:mm:ss");
          this.formData.lastOnlineTime = localTime2;
           //将日期转换为设备所在时区的本地时间
           const selectedTime3 = moment(this.formData.createTime);
          const deviceTimeZone3 = moment.tz.guess();
          const localTime3 = selectedTime3.tz(deviceTimeZone3).format("YYYY-MM-DD HH:mm:ss");
          this.formData.createTime = localTime3;
          console.log(this.formData);
          Axios.post("http://localhost:8080/device/add",this.formData)
            .then((res) => {
              console.log(res.data);
              this.tableData.push(this.formData);
              this.dialogVisible = false;
              this.$message({
                message: "提交成功",
                type: "success",
              });
              this.formData = {};
            })
            .catch((error) => {
              console.log(error);
              this.$message({
                message: "提交失败，请检查输入",
                type: "warning",
              });
            });
        } else {
          this.$message({
            message: "提交失败，请检查输入",
            type: "warning",
          });
        }
      });
    },
    handleDelete4() {
  for (let i = 0; i < this.selectedNames1.length; i++) {
    this.cunchushu1.push(this.selectedNames1[i].deviceId);
  } 
  this.$confirm('确定删除该设备记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    for(let i = 0; i<this.cunchushu1.length; i++)
    {
          Axios.delete(`http://localhost:8080/device/delete/${this.cunchushu1[i]}`).then(response => {
          console.log(response.data);
        }).catch(error => {
          console.error(error);
        });
    }
    // 遍历表格数据，找到所有在 this.cunchushu1 列表中的行的索引
    const indexesToDelete = [];
    for (let i = 0; i < this.tableData.length; i++) {
      const rowData = this.tableData[i];
      if (this.cunchushu1.includes(rowData.deviceId)) {
        indexesToDelete.push(i);
      }
    }
    // 从表格数据中删除这些行
    for (let i = indexesToDelete.length - 1; i >= 0; i--) {
      this.tableData.splice(indexesToDelete[i], 1);
    }
  }).catch(() => {
    // 取消删除操作
    this.$message({
      message: '已取消删除操作',
      type: 'info'
    });
  });
},
dateFilter(row, column) {
      return moment(row.activationTime).format("YYYY-MM-DD HH:mm:ss");
    },
    handleEditSubmit() {
      // 表单数据校验
      console.log(this.formData);
         //将日期转换为设备所在时区的本地时间
          const selectedTime = moment(this.formData.activationTime);
          const deviceTimeZone = moment.tz.guess();
          const localTime = selectedTime.tz(deviceTimeZone).format("YYYY-MM-DD HH:mm:ss");
          this.formData.activationTime = localTime;
           //将日期转换为设备所在时区的本地时间
           const selectedTime2 = moment(this.formData.lastOnlineTime);
          const deviceTimeZone2 = moment.tz.guess();
          const localTime2 = selectedTime2.tz(deviceTimeZone2).format("YYYY-MM-DD HH:mm:ss");
          this.formData.lastOnlineTime = localTime2;
           //将日期转换为设备所在时区的本地时间
           const selectedTime3 = moment(this.formData.createTime);
          const deviceTimeZone3 = moment.tz.guess();
          const localTime3 = selectedTime3.tz(deviceTimeZone3).format("YYYY-MM-DD HH:mm:ss");
          this.formData.createTime = localTime3;
          console.log(this.formData);
  this.$refs.form.validate((valid) => {
    if (valid) {
      // 发送编辑数据到后端更新数据
      Axios.post(`http://localhost:8080/device/update`, this.formData)
        .then((res) => {
          // 更新表格数据
          const index = this.tableData.findIndex(
            (item) => item.id === this.selectedRow.id
          );
          if (index !== -1) {
            this.tableData.splice(index, 1, this.formData);
          }
          // 关闭编辑对话框
          this.dialogVisible = false;
          this.$message({
            message: "修改成功",
            type: "success",
          });
        })
        .catch((error) => {
          console.log(error);
          this.$message({
            message: "修改失败，请检查输入",
            type: "warning",
          });
        });
    } else {
      this.$message({
        message: "修改失败，请检查输入",
        type: "warning",
      });
    }
  });
    },
  },
};
</script>

<style scoped>
.ghhjj{
  display:flex;
  margin:20px;
  align-items:justify-content;
}
.container {
  margin-top: 30px;
  margin: 30px;
}
.police1 {
  margin-right: 20px;
}
.input-container {
  align-items: center;
  margin-bottom: 10px;
  margin-left: 20px;
  display: inline-block;
}

.input-box {
  width: 300px;
  margin-right: 10px;
}

.search-btn {
  margin-left: 10px;
}

.table-container {
  position: relative;

  width: 100%;
}
.option {
  margin-left: 20px;
}
.psss{
  display: inline-block;
}
</style>